package cn.soqi.img;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.media.jai.JAI;
import javax.media.jai.RenderedOp;
import java.awt.color.ColorSpace;
import java.awt.color.ICC_ColorSpace;
import java.awt.color.ICC_Profile;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.io.*;

/**
 * RGB转CMYK
 *
 * @author brozer
 * @email 798121446@qq.com
 * @create 2017-05-08 14:16
 */
public class RgbToCmyk {
    static BASE64Encoder encoder = new sun.misc.BASE64Encoder();
    static BASE64Decoder decoder = new sun.misc.BASE64Decoder();


    static String getImageBinary(String fileName) {
        File f = new File(fileName);
        BufferedImage bi;
        try {
            InputStream inputStream = new FileInputStream(f);
            bi = ImageIO.read(inputStream);
            String fileType = getFileType(fileName);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            bi.flush();
            outputStream.flush();
            ImageIO.write(bi, fileType, outputStream);
            byte[] bytes = outputStream.toByteArray();
            outputStream.close();
            inputStream.close();
            return encoder.encodeBuffer(bytes).trim();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    static String getFileType(String fileName) {
        return fileName.substring(fileName.indexOf(".") + 1, fileName.length());
    }

    /**
     * 将其他格式的图片转换成CDR或其它文件格式
     *
     * @param sourceFileName
     * @param newFileName
     */
    static void base64StringToImage(String sourceFileName, String newFileName) {
        try {
            String base64String = getImageBinary(sourceFileName);
            byte[] bytes1 = decoder.decodeBuffer(base64String);
            ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes1);
            BufferedImage bi1 = ImageIO.read(inputStream);
            File w2 = new File(newFileName);//可以是jpg,png,gif格式
            ImageIO.write(bi1, getFileType(sourceFileName), w2);//不管输出什么格式图片，此处不需改动
            bi1.flush();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 将图片为rgb转化为cmyk
     *
     * @param inputStream 图片输入流
     * @param fileName    图片名词(绝对路径)
     * @param newFileName 图片保存路径（绝对路径）（如果没有参数，则生成的图片在当前目录下，且格式为tif）
     * @throws IOException
     */
    public static void rgbToCmyk(InputStream inputStream, String fileName, String... newFileName) throws IOException {

        BufferedImage rgbImage = ImageIO.read(inputStream);
        BufferedImage cmykImage = null;
        ColorSpace cpace = new ICC_ColorSpace(ICC_Profile.getInstance(RgbToCmyk.class.getClassLoader().getResourceAsStream("ISOcoated_v2_300_eci.icc")));
        ColorConvertOp op = new ColorConvertOp(rgbImage.getColorModel().getColorSpace(), cpace, null);
        cmykImage = op.filter(rgbImage, null);
        if (newFileName.length > 0 && newFileName[0] != null) {
            String targetFileName = fileName.substring(0, fileName.lastIndexOf(".") + 1) + "tif";
            RenderedOp renderOp = JAI.create("filestore", cmykImage, targetFileName, "TIFF");
            renderOp.dispose();
            cmykImage.flush();
            base64StringToImage(targetFileName, newFileName[0]);//转成对应格式
            File file = new File(fileName);
            if (file.exists())
                file.delete();
        } else {
            String targetFileName = fileName.substring(0, fileName.lastIndexOf(".") + 1) + "tif";
            JAI.create("filestore", cmykImage, targetFileName, "TIFF");
        }
    }

    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder();
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    public static void main(String[] args) throws IOException {
        //     System.out.println(getImageBinary());

        //base64StringToImage("C://Jellyfish.jpg","C://Jellyfish.tif");
      /*  String[] strs=ImageIO.getReaderFormatNames();
        File file=new File("C://Jellyfish.jpg");
        InputStream inputStream=new FileInputStream(file);
        rgbToCmyk(inputStream,"C://Jellyfish.jpg","C://abcd.cdr");*/
        //base64StringToImage("C://Jellyfish.png","C://Jellyfish.cdr");
        /*FileInputStream is = new FileInputStream("C://aaa.png");
        byte[] b = new byte[3];
        is.read(b, 0, b.length);
        System.out.println(bytesToHexString(b));*/


        File file = new File("C://Jellyfish.tif");
        String type = file.toURL().openConnection().getContentType();
        System.out.println(type);
        byte[] b = new byte[3];
        FileInputStream is = new FileInputStream(file);
        is.read(b, 0, b.length);
        System.out.println(bytesToHexString(b));
         /* tif转换到jpg格式 */
    /*    String input2 = "C://bbb.tif";
        String output2 = "C://bbb.jpeg";
        RenderedOp src2 = JAI.create("fileload", input2);
        OutputStream os2 = new FileOutputStream(output2);
        JPEGEncodeParam param2 = new JPEGEncodeParam();
        //指定格式类型，jpg 属于 JPEG 类型
        ImageEncoder enc2 = ImageCodec.createImageEncoder("JPEG", os2, param2);
        enc2.encode(src2);
        os2.close();
        */


    }




}
